<?php
namespace common\components;

use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use yii\rest\ActiveController;

Class BaseApiController extends ActiveController
{
    public $modelClass = "";

    public $enableCsrfValidation = false;

    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'items',
        // 'fieldsParam' => false
    ];

    /**
     * 响应成功标识
     * 用于平台响应统一ajax操作状态 与 getResponseArrForAjax一起使用
     * @var integer
     */
    const RESPONSE_SUCCESS = 1;
    const RESPONSE_DATA_URL = '_url';

    /**
     * 响应失败标识
     * @var integer
     */
    const RESPONSE_FAILURE = 0;

    public function actions($isEmpty = true)
    {
        return $isEmpty ? [] : parent::actions();
    }

    public function allowOrigin()
    {
        $headers = \Yii::$app->response->headers;
        $headers->set('Access-Control-Allow-Origin', '*');
    }

    public function beforeAction($action)
    {
        return parent::beforeAction($action);
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        unset($behaviors['rateLimiter'], $behaviors['authenticator']);
        return $behaviors;
    }

    protected function geneReqId()
    {
        return uniqid();
    }

    /**
     * 获取post
     * @param $key
     * @param string $default
     * @return array|mixed
     */
    public function post($key = null, $default = null)
    {
        return \Yii::$app->request->post($key, $default);
    }

    /**
     * 获取get
     * @param $key
     * @param string $default
     * @return array|mixed
     */
    public function get($key = null, $default = null) {
        return \Yii::$app->request->get($key, $default);
    }

    /**
     * 获取请求
     * @param null $key
     * @param null $default
     * @return array|mixed
     */
    public function requestAll($key = null, $default = null)
    {
        $requestParams = array_merge($this->get(), \Yii::$app->getRequest()->getBodyParams());

        if ( $key === null ) {
            return $requestParams;
        }
        return ArrayHelper::getValue($requestParams, $key, $default);
    }

    /**
     * 统一json响应
     * @param $status
     * @param $msg
     * @param $data
     * @return array
     */
    public function jsonResponse($status, $msg, $data = [])
    {
        if ( $data instanceof ActiveDataProvider ) {
            $data = $this->serializeData($data);
        }
        return ['status'=>$status, 'msg'=>$msg, 'data'=>$data];
    }

    //serializeData 转公用方法
    public function serialData($active){
        return $this->serializeData($active);
    }

    public function isPost()
    {
        return \Yii::$app->request->isPost;
    }

    public function isGet()
    {
        return \Yii::$app->request->isGet;
    }

    public function isAjax()
    {
        return \Yii::$app->request->isAjax;
    }
}